package com.darren.framework.utils;

import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;


public class EncryptAESUtil {
	
	protected static Logger logger = LogManager.getLogger(EncryptAESUtil.class);
	
	private final static String ALGORITHM = "AES";
	
	public EncryptAESUtil() {
		super();
	}
	
	/**
	 * 获取十六进制编码
	 * @param bytes
	 * @return
	 */
    private static String asHex(byte bytes[])
    {
        StringBuffer strbuf = new StringBuffer(bytes.length * 2);
        for (int i = 0; i < bytes.length; i++)
        {
            if (((int) bytes[i] & 0xff) < 0x10) strbuf.append("0");
            strbuf.append(Long.toString((int) bytes[i] & 0xff, 16));
        }        
        return strbuf.toString();
    }
   
    /**
     * 获取二进制编码
     * @param inputString
     * @return
     */
    private static byte[] asBin(String inputString){
		 if(inputString.length()<1){
			 return null;
		 }else{
			 byte[] encrypted = new byte[inputString.length()/2];
			 for(int i=0;i<inputString.length()/2;i++){
				  int high = Integer.parseInt(inputString.substring(i * 2, i * 2 + 1 ), 16);
				  int low = Integer.parseInt(inputString.substring(i * 2 + 1, i * 2 + 2), 16);
				 
				  encrypted[i] = (byte)(high * 16 + low);
			 }
			 return encrypted;
		 }
    }
   
    /**
     * get key
     * @return
     */
    public static String getRawKey() {    
	     try{
	         KeyGenerator kgen = KeyGenerator.getInstance(ALGORITHM);
	         kgen.init(128); 
	         SecretKey skey = kgen.generateKey();
	         byte[] raw = skey.getEncoded();
	         return asHex(raw);
	     }catch (Exception e) {
	    	 System.out.println("Exception in getRawKey:"+ e);
	         return null;
	     }
    }

    /**
     * 用密钥rawKey给输入字符串inputString加密
     * @param inputString
     * @param rawKey
     * @return
     */
    public static String getEncryption(String inputString, String rawKey){
    	if(inputString == null || rawKey == null){
    		return null;
    	}
    	if("".equals(inputString)){
    		return "";
    	}
    	byte[] key = asBin(rawKey);
        try{   
	         SecretKeySpec skeySpec = new SecretKeySpec(key, ALGORITHM);        
	         Cipher cipher = Cipher.getInstance(ALGORITHM);
	         cipher.init(Cipher.ENCRYPT_MODE, skeySpec);	
	         byte[] encrypted = cipher.doFinal(inputString.getBytes());	        
	         return asHex(encrypted);
        }catch (Exception e) {
        	logger.info("Exception in Encryption:"+ e);
        	return null;
        }
    }
   
    /**
     * 用密钥rawKey给加密字符串encryptString解密
     * decrypt the encryptString with key rawKey
     * @param encryptString
     * @param rawKey
     * @return
     */
	public static String getDecryption(String encryptString, String rawKey) {
		if (encryptString == null || rawKey == null) {
			return null;
		}
		if (encryptString.equals("")) {
			return "";
		}

		byte[] tmp = asBin(encryptString);
		byte[] key = asBin(rawKey);

		try {
			SecretKeySpec skeySpec = new SecretKeySpec(key, ALGORITHM);
			Cipher cipher = Cipher.getInstance(ALGORITHM);
			cipher.init(Cipher.DECRYPT_MODE, skeySpec);
			byte[] decrypted = cipher.doFinal(tmp);
			return new String(decrypted);
		} catch (Exception e) {
			logger.info("Exception in Decryption:" + e);
			return null;
		}
	}

}
